package cn.zjitc.jdbc.service.impl;

import cn.zjitc.jdbc.domain.Account;
import cn.zjitc.jdbc.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("accountService")
public class AccountServiceImpl implements AccountService {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void transfer(Account from, Account to, double money) {
        Account fromAccount = findById(from.getId());
        fromAccount.setMoney(fromAccount.getMoney()-money);
        Account toAccount = findById(to.getId());
        toAccount.setMoney(toAccount.getMoney()+money);
        update(fromAccount);
        int r=1/0;
        update(toAccount);
    }

    @Override
    public void update(Account account) {
        jdbcTemplate.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());

    }

    @Override
    public Account findById(Integer id) {

        return jdbcTemplate.queryForObject("select * from account where id=?",new BeanPropertyRowMapper<>(Account.class),id);
    }

    @Override
    public void save(Account account) {
        jdbcTemplate.update("insert into account(name,money) values(?,?)",account.getName(),account.getMoney());
    }

    @Override
    public void deleteById(Integer id) {
        jdbcTemplate.update("delete from account where id=?",id);

    }

    @Override
    public List<Account> findAll() {
       return jdbcTemplate.query("select * from account",new BeanPropertyRowMapper<>(Account.class));
    }
}
